<template>
  <el-dialog
      title="检查任务"
      v-model="dialogVisible"
      width="1400px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
      @open="resetCheckTaskList"
  >
    <div class="task-header">
      <h3>{{ elder?.elderName }}的检查任务</h3>
      <div class="search-group">
        <el-date-picker
            v-model="searchParams.date"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
            :locale="zhCn"
        />

        <!-- 搜索按钮 -->
        <el-button type="primary" @click="handleSearch">搜索</el-button>

        <!-- 重置按钮 -->
        <el-button @click="resetSearch">重置</el-button>
      </div>
      <el-button type="primary" :icon="Plus" @click="handleAddTask">添加任务</el-button>
    </div>
    <el-table :data="props.elder?.checkTasks" style="width: 100%" border stripe>
      <el-table-column prop="date" label="检查日期" width="120" align="center"/>
      <el-table-column label="检查类型" width="180" align="center">
        <template #default="{ row }">
          {{ row.checkTypes?.name || '未知类型' }}
        </template>
      </el-table-column>
      <el-table-column prop="doctorName" label="负责医生" width="120" align="center"/>
      <el-table-column label="完成状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="row.finish ? 'success' : 'warning'">
            {{ row.finish ? '已完成' : '未完成' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否异常" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="tagType(row).type">
            {{ tagType(row).text }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="result" label="检查结果" min-width="300" show-overflow-tooltip align="center"/>
      <el-table-column label="操作" width="200" fixed="right" align="center">
        <template #default="{ row }">
          <el-button type="primary" :icon="Edit" @click="handleEditTask(row)">编辑</el-button>
          <el-button type="danger" :icon="Delete" @click="handleDeleteTask(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 检查任务表单对话框 -->
    <check-task-form-dialog
        v-model="showTaskForm"
        :elder="elder"
        :task="currentTask"
        :check-types="checkTypes"
        :doctor-list="filteredDoctorList"
        @success="handleSuccess"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import {computed, onMounted, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Delete, Edit, Plus} from '@element-plus/icons-vue'
import type {Elder} from '@/types/elder'
import {deleteCheckTask, ElderAndDate, getElderCheckTasks} from '@/api/checkTask'
import CheckTaskFormDialog from './CheckTaskFormDialog.vue'
import {CheckType} from "@/types/checkType";
import {Doctor} from "@/types/doctor";
import {CheckTask} from "@/types/checkTask";
import zhCn from "element-plus/es/locale/lang/zh-cn";
import {getAllCheckTypes} from "@/api/checkType";
import {getAllDoctors} from "@/api/doctor";

const checkTypes = ref<CheckType[]>([])
const doctorList = ref<Doctor[]>([])

// 获取检查类型列表
const fetchCheckTypes = async () => {
  try {
    checkTypes.value = await getAllCheckTypes()
  } catch (error) {
    console.error('获取检查类型列表失败:', error)
  }
}

// 获取医生列表
const fetchDoctorList = async () => {
  try {
    doctorList.value = await getAllDoctors()
  } catch (error) {
    console.error('获取医生列表失败:', error)
  }
}

const tagType = (row) => {
  if (!row.finish && !row.hasQuestion) return {type: 'warning', text: '待检测'}
  if (row.finish && row.hasQuestion) return {type: 'danger', text: '异常'}
  if (row.finish && !row.hasQuestion) return {type: 'success', text: '正常'}
  return {type: '', text: ''}
}

const searchParams = ref({
  date: ''
})

// 搜索方法
const handleSearch = () => {
  fetchCheckTaskList();
}

// 对话框关闭处理
const handleDialogClose = () => {
  // 重置搜索条件
  searchParams.value = {
    date: ''
  }
}


// 重置搜索
const resetSearch = async () => {
  searchParams.value = {
    date: '',
  };
  await resetCheckTaskList()
}

const resetCheckTaskList = async () => {
  await fetchCheckTypes()
  await fetchDoctorList()
  const res = await getElderCheckTasks({
    elderId: props.elder?.id,
    date: ''
  })

  if (props.elder) {
    props.elder.checkTasks = res
  }
}

const fetchCheckTaskList = async () => {
  const res = await getElderCheckTasks(<ElderAndDate>{
    elderId: props.elder?.id,
    date: searchParams.value.date
  })

  if (props.elder) {
    props.elder.checkTasks = res
  }
}

const props = defineProps<{
  modelValue: boolean
  elder: Elder | undefined
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}>()

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 在script setup部分添加计算属性
const filteredDoctorList = computed(() => {
  if (!props.elder || !doctorList.value.length) return []
  return doctorList.value.filter(doctor =>
      doctor.communityId === props.elder?.communityId
  )
})

const showTaskForm = ref(false)
const currentTask = ref<CheckTask>()

// 在父组件中添加
const handleAddTask = () => {
  currentTask.value = undefined // 确保设置为undefined
  showTaskForm.value = true
}

// 编辑检查任务
const handleEditTask = (task: CheckTask) => {
  currentTask.value = task
  showTaskForm.value = true
}

// 删除检查任务
const handleDeleteTask = async (task: CheckTask) => {
  try {
    await ElMessageBox.confirm('确认删除该检查任务吗？', '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })
    await deleteCheckTask(task.id)
    ElMessage.success('删除成功')
    await handleSuccess()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

// 操作成功回调
const handleSuccess = async () => {
  if (!props.elder) return
  try {
    props.elder.checkTasks = await getElderCheckTasks({elderId: props.elder.id})
  } catch (error) {
    console.error('获取检查任务列表失败:', error)
  }
  emit('success')
}
</script>

<style scoped>
.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.task-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: normal;
  color: #303133;
}

.search-group {
  display: flex;
  align-items: center;
  gap: 10px; /* 统一设置元素间间距 */
}

/* 统一输入框和按钮的宽度和间距 */
.search-group .el-input,
.search-group .el-select,
.search-group .el-button {
  margin: 0; /* 清除默认margin */
}

:deep(.el-button) {
  transition: all 0.3s;
  padding: 0 15px;
  font-size: 14px;
}

:deep(.el-button:hover) {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

:deep(.el-button--primary) {
  background-color: #409eff;
  border-color: #409eff;
  color: #fff;
}

:deep(.el-button--primary:hover) {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

:deep(.el-button--danger) {
  background-color: #f56c6c;
  border-color: #f56c6c;
  color: #fff;
}

:deep(.el-button--danger:hover) {
  background-color: #f78989;
  border-color: #f78989;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa !important;
}

:deep(.el-table--border) {
  border: 1px solid #ebeef5;
}

:deep(.el-table--border th),
:deep(.el-table--border td) {
  border-right: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
}
</style>